﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization.Json;
using FortuneHeaven.Admin.Common;
using System.Web.Script.Serialization;
using Jzy.Core.Common.Basic;
using FortuneHeavenCommon.ComMethod;

namespace FortuneHeaven.Admin.CMS
{
    /// <summary>
    /// ImageHandler 的摘要说明
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        private HttpContext Context = null;
        public void ProcessRequest(HttpContext context)
        {
            
            HttpPostedFile imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                showError("请选择文件。");
                return;
            }
            string errorinfor = "";
            string returl = "";
            bool succeed = ImagesManager.SaveCMSImg(context,ref returl,ref errorinfor);

            if (!succeed)
            {
                showError(errorinfor);
                return;
            }
            Hashtable table = new Hashtable();
            table["error"] = 0;
            table["url"] = "http://" +context.Request.Url.Authority + GlobalVar.WebAppPath + CommonPath.CMS + returl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            JavaScriptSerializer js = new JavaScriptSerializer();
            string output = js.Serialize(table);
            context.Response.Write(output); 
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void showError(string message)
        {
             Dictionary<string, object> dic  = new  Dictionary<string, object> ();
            dic["error"] = 1;
            dic["message"] = message;

            Context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Dictionary<string, object>));

            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, dic);
                Context.Response.Write(ms.ToArray());
            }
            Context.Response.End();
        }

    }
}